package com.example.controller;

import com.common.result.Result;
import com.example.exception.createException.DeletionNotAllowedException;
import com.example.service.CategoryService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.pojo.dto.CategoryDTO;
import com.pojo.dto.QueryPageDTO;
import com.pojo.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/admin/category")
@RestController
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 查询所有菜品分类
     */
    @GetMapping
    public Result AllList(){
        List<Category> categoryList = categoryService.allList();
        return Result.success(categoryList);
    }

    /**
     * 分页查询
     * @param queryPageDTO
     * @return
     */
    @GetMapping("/page")
    @ResponseBody
    public Result page(QueryPageDTO queryPageDTO){
        Page<Category> p = categoryService.page(queryPageDTO);
        PageInfo<Category> result = new PageInfo<>(p.getResult());
        return Result.success(result);
    }

    /**
     * 新增分类
     * @param categoryDTO
     * @return
     */
    @PostMapping
    @ResponseBody
    public Result save(@RequestBody CategoryDTO categoryDTO){
        categoryService.save(categoryDTO);
        return Result.success("添加分类成功");
    }

    /**
     * 根据id删除分类
     * @param id
     * @return
     */
    @DeleteMapping
    @ResponseBody
    public Result deleteById(Long id) throws DeletionNotAllowedException {
        categoryService.deleteById(id);
        return Result.success("删除成功");
    }

    /**
     * 修改分类
     * @param categoryDTO
     * @return
     */
    @PutMapping
    @ResponseBody
    public Result update(@RequestBody CategoryDTO categoryDTO){
        categoryService.update(categoryDTO);
        return Result.success();
    }

    @GetMapping("/{id}")
    @ResponseBody
    public Result getById(@PathVariable Long id){
        Category category = categoryService.getById(id);
        return Result.success(category);
    }

}
